<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getOrderListApi, getOrderDetailApi } from "@/api/order-manage"
import { type OrderData, type GetOrderListRequestData } from "@/api/order-manage/types/order"
import { type FormInstance, ElMessage } from "element-plus"
import { Search, Refresh, Download, RefreshRight, View } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

defineOptions({
  // 命名当前组件
  name: "OrderList"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 订单详情弹窗
const detailDialogVisible = ref<boolean>(false)
const orderDetail = ref<OrderData | null>(null)

const handleViewDetail = async (row: OrderData) => {
  try {
    loading.value = true
    const { data } = await getOrderDetailApi(row.id)
    orderDetail.value = data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error("获取订单详情失败")
  } finally {
    loading.value = false
  }
}

// 查询订单数据
const orderData = ref<OrderData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  id: "",
  customerPhone: "",
  merchantName: "",
  status: "",
  deliveryType: "",
  receiverName: "",
  receiverPhone: "",
  startTime: "",
  endTime: ""
})

const getOrderData = () => {
  loading.value = true
  const params: GetOrderListRequestData = {
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    id: searchData.id || undefined,
    customerPhone: searchData.customerPhone || undefined,
    merchantName: searchData.merchantName || undefined,
    status: searchData.status ? Number(searchData.status) : undefined,
    deliveryType: searchData.deliveryType ? Number(searchData.deliveryType) : undefined,
    receiverName: searchData.receiverName || undefined,
    receiverPhone: searchData.receiverPhone || undefined,
    startTime: searchData.startTime || undefined,
    endTime: searchData.endTime || undefined
  }
  
  getOrderListApi(params)
    .then(({ data }) => {
      paginationData.total = data.total
      orderData.value = data.list
    })
    .catch(() => {
      orderData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getOrderData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 状态映射
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: "待付款",
    2: "待接单",
    3: "进行中",
    4: "已完成",
    5: "已取消"
  }
  return statusMap[status] || "未知"
}

const getStatusType = (status: number): "success" | "warning" | "info" | "primary" | "danger" => {
  const typeMap: Record<number, "success" | "warning" | "info" | "primary" | "danger"> = {
    1: "warning",
    2: "info",
    3: "primary",
    4: "success",
    5: "danger"
  }
  return typeMap[status] || "info"
}

const getDeliveryTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "外卖",
    2: "堂食",
    3: "自取"
  }
  return typeMap[type] || "未知"
}

// 格式化规格信息
const formatSpecifications = (specsStr: string) => {
  if (!specsStr) return "-"
  try {
    const specs = JSON.parse(specsStr)
    if (!Array.isArray(specs)) return specsStr
    return specs.map(spec => spec.value).join(",")
  } catch (e) {
    return specsStr
  }
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getOrderData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="订单ID">
          <el-input v-model="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="customerPhone" label="顾客电话">
          <el-input v-model="searchData.customerPhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="merchantName" label="商户名称">
          <el-input v-model="searchData.merchantName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="status" label="订单状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="待付款" value="1" />
            <el-option label="待接单" value="2" />
            <el-option label="进行中" value="3" />
            <el-option label="已完成" value="4" />
            <el-option label="已取消" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item prop="deliveryType" label="配送类型">
          <el-select v-model="searchData.deliveryType" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="外卖" value="1" />
            <el-option label="堂食" value="2" />
            <el-option label="自取" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="receiverName" label="收货人">
          <el-input v-model="searchData.receiverName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="receiverPhone" label="收货人电话">
          <el-input v-model="searchData.receiverPhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- 订单管理不需要新增和删除按钮 -->
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getOrderData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="orderData">
          <el-table-column prop="id" label="订单ID" align="center" width="180" />
          <el-table-column prop="customerPhone" label="顾客电话" align="center" width="120" />
          <el-table-column prop="merchantName" label="商户名称" align="center" width="150" />
          <el-table-column label="商户Logo" align="center" width="80">
            <template #default="scope">
              <el-image 
                v-if="scope.row.merchantLogo" 
                :src="scope.row.merchantLogo" 
                style="width: 40px; height: 40px" 
                fit="cover"
                :preview-src-list="[scope.row.merchantLogo]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
                <template #error>
                  <el-icon>
                    <Loading />
                  </el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" align="center" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" effect="plain" disable-transitions>
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deliveryType" label="配送类型" align="center" width="100">
            <template #default="scope">
              <el-tag type="info" effect="plain" disable-transitions>
                {{ getDeliveryTypeText(scope.row.deliveryType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="actualPay" label="实付金额" align="center" width="100">
            <template #default="scope">
              <span class="text-red-500 font-bold">¥{{ scope.row.actualPay }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="receiverName" label="收货人" align="center" width="100" />
          <el-table-column prop="receiverPhone" label="收货人电话" align="center" width="120" />
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" :icon="View" @click="handleViewDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="orderDetail" class="order-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="订单ID">{{ orderDetail.id }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :type="getStatusType(orderDetail.status)" effect="plain">
                  {{ getStatusText(orderDetail.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="配送类型">
                <el-tag type="info" effect="plain">
                  {{ getDeliveryTypeText(orderDetail.deliveryType) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
              <el-descriptions-item label="支付时间">{{ orderDetail.payTime || '未支付' }}</el-descriptions-item>
              <el-descriptions-item label="完成时间">{{ orderDetail.finishTime || '未完成' }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="商户信息" :column="1" border>
              <el-descriptions-item label="商户名称">{{ orderDetail.merchantName }}</el-descriptions-item>
              <el-descriptions-item label="商户电话">{{ orderDetail.merchantPhone }}</el-descriptions-item>
              <el-descriptions-item label="商户Logo">
                <el-image 
                  v-if="orderDetail.merchantLogo" 
                  :src="orderDetail.merchantLogo" 
                  style="width: 60px; height: 60px" 
                  fit="cover"
                  :preview-src-list="[orderDetail.merchantLogo]"
                />
                <span v-else>无图片</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-descriptions title="收货信息" :column="1" border>
              <el-descriptions-item label="收货人">{{ orderDetail.receiverName }}</el-descriptions-item>
              <el-descriptions-item label="收货电话">{{ orderDetail.receiverPhone }}</el-descriptions-item>
              <el-descriptions-item label="收货地址">{{ orderDetail.deliveryAddress }}</el-descriptions-item>
              <el-descriptions-item label="备注">{{ orderDetail.remark || '无' }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="价格信息" :column="1" border>
              <el-descriptions-item label="订单金额">¥{{ orderDetail.totalPrice }}</el-descriptions-item>
              <el-descriptions-item label="配送费">¥{{ orderDetail.deliveryFee }}</el-descriptions-item>
              <el-descriptions-item label="打包费">¥{{ orderDetail.totalPackagingFee }}</el-descriptions-item>
              <el-descriptions-item label="优惠金额">¥{{ orderDetail.discount }}</el-descriptions-item>
              <el-descriptions-item label="实付金额">
                <span class="text-red-500 font-bold text-lg">¥{{ orderDetail.actualPay }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
        
        <div style="margin-top: 20px;">
          <el-descriptions title="商品信息" :column="1" border>
            <el-descriptions-item label="商品列表">
              <el-table :data="orderDetail.goods" style="width: 100%">
                <el-table-column prop="name" label="商品名称" />
                <el-table-column label="商品图片" width="80">
                  <template #default="scope">
                    <el-image 
                      v-if="scope.row.image" 
                      :src="scope.row.image" 
                      style="width: 40px; height: 40px" 
                      fit="cover"
                      :preview-src-list="[scope.row.image]"
                    />
                    <span v-else>无图片</span>
                  </template>
                </el-table-column>
                <el-table-column label="规格" width="120">
                  <template #default="scope">
                    {{ formatSpecifications(scope.row.specifications) }}
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="单价">
                  <template #default="scope">
                    ¥{{ scope.row.price }}
                  </template>
                </el-table-column>
                <el-table-column prop="quantity" label="数量" />
                <el-table-column prop="totalPrice" label="小计">
                  <template #default="scope">
                    ¥{{ scope.row.totalPrice }}
                  </template>
                </el-table-column>
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: center;
}

.order-detail {
  .el-descriptions {
    margin-bottom: 20px;
  }
}
</style>